package org.wingstudio.controller.admin;

import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.wingstudio.entity.PageBean;
import org.wingstudio.entity.Source;
import org.wingstudio.entity.SourceType;
import org.wingstudio.lucene.SourceIndex;
import org.wingstudio.service.SourceService;
import org.wingstudio.service.SourceTypeService;
import org.wingstudio.util.AsposeUtil;
import org.wingstudio.util.PageUtil;
import org.wingstudio.util.ResponseUtil;
import org.wingstudio.util.StringUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liao on 16-12-2.
 */

@Controller
@RequestMapping("/user/admin")
public class SourceController {


    @Resource
    private SourceService sourceService;
    @Resource
    private SourceTypeService sourceTypeService;

    private SourceIndex sourceIndex=new SourceIndex();
    @RequestMapping("/addSource")
    public ModelAndView addSource(){
        ModelAndView modelAndView=new ModelAndView();
        List<SourceType> sourceTypes=sourceTypeService.countList();
        modelAndView.addObject("sourceTypes",sourceTypes);
        modelAndView.setViewName("user/admin/build/source");
        return modelAndView;
    }

    @RequestMapping(value = "/uploadSource", method = RequestMethod.POST)
    public String uploadSource(HttpServletRequest request,
                               HttpServletResponse response,
                         @RequestParam("file") MultipartFile file, ModelMap model,
                         org.wingstudio.entity.Source source) throws Exception{

        String path = request.getSession().getServletContext().getRealPath("/static/source");
        String pathSourcePDF = request.getSession().getServletContext().getRealPath("/static/sourcePDF");
        String testFileName = file.getOriginalFilename();
        String prefix=testFileName.substring(testFileName.lastIndexOf(".")+1);
        String name=String.valueOf(Calendar.getInstance().getTimeInMillis());
        String sourceName=name+"."+prefix;
        String sourceNamePDF=name+".pdf";
        source.setSourceName(sourceNamePDF);
        long fileSize2=file.getSize();
        if((fileSize2/1024)<1000){
            String fileSize3=String.valueOf(fileSize2/1024)+"KB";
            source.setSourceSize(fileSize3);
        }else{
            String fileSize3=String.valueOf(fileSize2/1048576)+"M";
            source.setSourceSize(fileSize3);
        }

        File targetFile = new File(path, sourceName);
        sourceService.add(source);
        Source testSource=sourceService.getLast();
        sourceIndex.addIndex(testSource);

        if (prefix.equals("pdf")){
            File targetFile1 = new File(pathSourcePDF, sourceNamePDF);
            // 保存原文件
            try {
                file.transferTo(targetFile1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else {
            File targetFile2 = new File(path, sourceName);
            // 保存原文件
            try {
                file.transferTo(targetFile2);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if(prefix.equals("doc")||prefix.equals("docx")||prefix.equals("txt")
                ||prefix.equals("excel")){
            try{
                AsposeUtil.docToPdf(path+"/"+sourceName,
                        pathSourcePDF+"/"+name+".pdf");
            }catch (Exception e){
                System.out.println(e);
            }
        }
        model.addAttribute("fileUrl", request.getContextPath() + "/static/files/" + sourceName);
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/deleteSource")
    public String deleteSource(@RequestParam(value="id")String id,HttpServletResponse response)
            throws Exception{
        System.out.println("test source id:"+id);
        sourceService.delete(Integer.parseInt(id));
        JSONObject result=new JSONObject();
        result.put("success", true);
        ResponseUtil.write(response, result);
        return null;
    }

    @RequestMapping("/general")
    public ModelAndView listGenarals(@RequestParam(value="page",required=false)String page,
                                     HttpServletRequest request)
            throws Exception{
        System.out.println("test");
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("sourceTypeId",1);
        List<Source> generalList=sourceService.listSource(map);

        Long sum=sourceService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/general",
                sourceService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("generalList",generalList);
        modelAndView.setViewName("user/admin/source/generalManage");
        return modelAndView;
    }

    @RequestMapping("/learn")
    public ModelAndView listLearns(@RequestParam(value="page",required=false)String page,
                                   HttpServletRequest request)
            throws Exception{
        System.out.println("test");
        ModelAndView modelAndView=new ModelAndView();
        if(StringUtil.isEmpty(page)){
            page="1";
        }
        PageBean pageBean=new PageBean(Integer.parseInt(page),10);
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", pageBean.getStart());
        map.put("size", pageBean.getPageSize());
        map.put("sourceTypeId",2);
        List<Source> learnList=sourceService.listSource(map);

        Long sum=sourceService.getTotal(map);
        modelAndView.addObject("sum",sum);
        modelAndView.addObject("pageCode", PageUtil.genPagination(request.getContextPath()+"/user/admin/learn",
                sourceService.getTotal(map), Integer.parseInt(page), 10));
        modelAndView.addObject("learnList",learnList);
        modelAndView.setViewName("user/admin/source/learnManage");
        return modelAndView;
    }

    @RequestMapping("/searchSource")
    public ModelAndView search(HttpServletRequest request)throws Exception{
        ModelAndView modelAndView=new ModelAndView();
        String content=request.getParameter("content");
        System.out.println("测试传入的值："+content);
        List<Source> sourceList=sourceIndex.searchSource(content);
        System.out.println("test newSource:"+sourceList.size());

        modelAndView.addObject("sourceList",sourceList);
        modelAndView.setViewName("user/admin/source/searchResult");
        return modelAndView;
    }

}
